#!/usr/bin/env python3
# $Id: beryl.py ddcad87fab9c 2013/08/17 19:20:30 pgurumur $
#
# Copyright (c) 2009 Prabhu Gurumurthy  <pgurumur@gmail.com>
# 
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# File generated on Sat Aug 25, 2012 @ 00:44:54

__version__ = "$Revision: ddcad87fab9c $"
__author__ = "$Author: pgurumur $"
__modified__ = "$Date: 2013-08-17 19:20:30Z $"

import os
import optparse
import signal
import sys

from emerald.lib import exception, cmdparser, scarlet

class beryl(cmdparser.GetOpt):
   option_list = (
         optparse.make_option("-d", "--debug", action = "store_true",
            help = "Turn on debugging", default = False, dest = "debug"),
         ) + cmdparser.GetOpt.option_list

   help = """

   Simple scripting language based on python3 and pyparsing
   """

   usage = "[ options ] file"

   def sighandle(self, signal, frame):
      print("\n")
      self.error("program with pid %d terminated with signal: %d",
            os.getpid(), signal)

   @cmdparser.getopts
   def handle(self):
      signal.signal(signal.SIGTERM, self.sighandle)
      signal.signal(signal.SIGINT, self.sighandle)
      signal.signal(signal.SIGHUP, self.sighandle)

      inputfile = None
      stdin = False
      try:
         inputfile = self.arguments[1]
         if inputfile == "-":
            inputfile = sys.stdin
            stdin = True
         else:
            if not os.path.exists(inputfile):
               self.error("%s: %s does not exist", str(self), inputfile)
      except IndexError:
         inputfile = sys.stdin
         stdin = True

      if stdin:
         sys.stdout.flush()
         print("To exit, press Ctrl-C followed Ctrl-D")

      try:
         scarlet.parser(inputfile, stdin)
      except exception.LexerError as err:
         self.error(str(err).format('utf-8'))

if __name__ == "__main__":
   lang = None
   try:
      lang = beryl(version = 0.1, args = sys.argv)
      lang.handle()
   except exception.GetOptError as err:
      print(err)
      sys.exit(1)

